package com.apes.fn.fico.invoiceApply.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.Arith;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fn.fico.invoiceApply.model
 * @ClassName: InvoiceApply
 * @Author: pyb
 * @Description: 直营发票申请
 * @CreateTime: 2021-04-08 15:35
 * @Version: 1.0
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = DirectInvoiceApply.CONST_TABLE_NAME)
public class DirectInvoiceApply extends Model {
    public static final String CONST_TABLE_NAME = "acc_direct_invoice_apply";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "发票申请", padding = 8, prefix = "%(company)")
    @Comment("发票申请单号")
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "invoice_type", referencedColumnName = "id")
    @Comment("发票类型")
    private Enumeration invoiceType;


    @Column(name = "sale_category", length = 32)
    @Comment("销售类别")
    private String saleCategory;

    @Column(name = "email", length = 32)
    @Comment("邮箱")
    private String email;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    @Comment("公司编码")
    private PartyRole company;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "invoice_company_id", referencedColumnName = "id")
    @Comment("开票公司编码")
    private PartyRole invoiceCompany;

    @Comment("部门")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    private Dept dept;


    @Column(name = "buyer_name", length = 60)
    @Comment("购方名称")
    private String buyerName;

    @Column(name = "buyer_info", length = 120)
    @Comment("购方信息")
    private String buyerInfo;


    @Column(name = "buyer_tax_number", length = 60)
    @Comment("购方税号")
    private String buyerTaxNumber;


    @Column(name = "buyer_bank_info", length = 120)
    @Comment("购方银行信息")
    private String buyerBankInfo;

    @Column(name = "invoice_number", length = 256)
    @Comment("发票号码")
    private String invoiceNumber;
//
//    @Column(name = "info", length = 256)
//    @Comment("单据信息")
//    private String info;

//    @Comment("车主信息")
//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "customer_expand_id", referencedColumnName = "id")
//    private FnCustomerExpand carInfo;

    @States(name = "单据状态", values = {
            @State(id = "sent", name = "制单"),
            @State(id = "apply", name = "申请"),
            @State(id = "approve", name = "审核"),
            @State(id = "accounting", name = "核算"),
//            @State(id = "register", name = "登记发票号"),
            @State(id = "stop", name = "已终止"),
    })
    @Column(name = "state", length = 36, nullable = false)
    private String state;


    @Column(name = "total_sale_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("销售金额合计")
    private double totalSaleAmount = 0;

    @Column(name = "actual_invoiced_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("实际开票金额")
    private double actualInvoicedAmount = 0;


    @Column(name = "invoiced_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("开票金额")
    private double invoicedAmount = 0;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "apply_id", referencedColumnName = "id")
    @Comment("申请人")
    private PartyRole applyId;

    @Column(name = "apply_date")
    @Comment("申请日期")
    private Date applyDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_id", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveId;

    @Column(name = "approve_date")
    @Comment("审核日期")
    private Date approveDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "register_id", referencedColumnName = "id")
    @Comment("登记人")
    private PartyRole registerId;

    @Column(name = "register_date")
    @Comment("登记日期")
    private Date registerDate;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "revoker_id", referencedColumnName = "id")
    @Comment("发票收回人")
    private PartyRole revokeId;

    @Column(name = "revoke_date")
    @Comment("发票收回日期")
    private Date revokeDate;

    @Column(name = "note", length = 250)
    @Comment("备注")
    private String note; //备注

    @Column(name = "need_oa", nullable = false, columnDefinition = ApesConst.FIELD_BOOLEAN_TRUE)
    @Comment("是否转OA")
    private boolean needOa = true;
//
//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "accounting_id", referencedColumnName = "id")
//    @Comment("核算人")
//    private PartyRole accountingId;
//
//    @Column(name = "accounting_date")
//    @Comment("核算日期")
//    private Date accountingDate;

    @OneToMany(mappedBy = "invoiceApply", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<DirectInvoiceApplyItem> invoiceApplyItems = new ArrayList<>();

    public List<DirectInvoiceApplyItem> getInvoiceApplyItems() {
        for (DirectInvoiceApplyItem invoiceApplyItem : invoiceApplyItems) {
            invoiceApplyItem.setInvoiceApply(this);
        }
        return invoiceApplyItems;
    }


    public void computeAmt() {
        totalSaleAmount = invoiceApplyItems.stream().map(item -> Arith.sub(item.getPriceTotal(), item.getDiscountAmount())).reduce(Arith::add).orElse(0.0);
        invoicedAmount = invoiceApplyItems.stream().map(DirectInvoiceApplyItem::getActualInvoicedAmount).reduce(Arith::add).orElse(0.0);
        if (invoicedAmount < actualInvoicedAmount) {
            throw new RuntimeException("实际开票金额不能大于开票金额");
        }

    }
    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if(this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }
}
